#include "DSP2833x_Device.h"
#include "DSP2833x_GlobalPrototypes.h"

#pragma CODE_SECTION(sciaTxFifoIsr, "ramfuncs");
#pragma CODE_SECTION(sciaRxFifoIsr, "ramfuncs");
#pragma CODE_SECTION(scibTxFifoIsr, "ramfuncs");
#pragma CODE_SECTION(scibRxFifoIsr, "ramfuncs");
#pragma CODE_SECTION(scicRxFifoIsr, "ramfuncs");

void UARTDriverAInt();
void UARTDriverAIntRX();
void UARTDriverBInt();
void UARTDriverBIntRX();
void UARTDriverCInt();

interrupt void sciaTxFifoIsr(void)
{
	UARTDriverAInt();
	
	SciaRegs.SCIFFTX.bit.TXFFINTCLR=1;	// Clear SCI Interrupt flag
	PieCtrlRegs.PIEACK.all|=0x100;      // Issue PIE ACK
}

interrupt void sciaRxFifoIsr(void)
{
	UARTDriverAIntRX();
	
	SciaRegs.SCIFFRX.bit.RXFFOVRCLR=1;   // Clear Overflow flag
	SciaRegs.SCIFFRX.bit.RXFFINTCLR=1;	// Clear SCI Interrupt flag
	PieCtrlRegs.PIEACK.all|=0x100;      // Issue PIE ACK
}

interrupt void scibTxFifoIsr(void)
{
	UARTDriverBInt();
	
	ScibRegs.SCIFFTX.bit.TXFFINTCLR=1;	// Clear SCI Interrupt flag
	PieCtrlRegs.PIEACK.all|=0x100;      // Issue PIE ACK
}

interrupt void scibRxFifoIsr(void)
{
	UARTDriverBIntRX();
	
	ScibRegs.SCIFFRX.bit.RXFFOVRCLR=1;   // Clear Overflow flag
	ScibRegs.SCIFFRX.bit.RXFFINTCLR=1;	// Clear SCI Interrupt flag
	PieCtrlRegs.PIEACK.all|=0x100;      // Issue PIE ACK
}

interrupt void scicRxFifoIsr(void)
{
	UARTDriverCInt();
	
	ScicRegs.SCIFFRX.bit.RXFFOVRCLR=1;   // Clear Overflow flag
	ScicRegs.SCIFFRX.bit.RXFFINTCLR=1;	// Clear SCI Interrupt flag
	PieCtrlRegs.PIEACK.all|=0x080;      // Issue PIE ACK
}

extern Uint16 RamfuncsLoadStart;
extern Uint16 RamfuncsLoadEnd;
extern Uint16 RamfuncsRunStart;

void SysInit()
{
	// Init INTS
	DINT;
	
	InitPieCtrl();
	// Disable CPU interrupts and clear all CPU interrupt flags:
	IER = 0x0000;
	IFR = 0x0000;
	InitPieVectTable();
	
	EALLOW;	
	PieVectTable.SCITXINTA = &sciaTxFifoIsr;
	PieVectTable.SCIRXINTA = &sciaRxFifoIsr;
	PieVectTable.SCITXINTB = &scibTxFifoIsr;
	PieVectTable.SCIRXINTB = &scibRxFifoIsr;
	PieVectTable.SCIRXINTC = &scicRxFifoIsr;
	EDIS;
	
	MemCopy(&RamfuncsLoadStart, &RamfuncsLoadEnd, &RamfuncsRunStart);
	
	// Enable interrupts
	PieCtrlRegs.PIECTRL.bit.ENPIE = 1;   // Enable the PIE block
	PieCtrlRegs.PIEIER9.bit.INTx1=1;     // PIE Group 9, INT1, RX SCI-A
	PieCtrlRegs.PIEIER9.bit.INTx2=1;     // PIE Group 9, INT2, TX SCI-A
	PieCtrlRegs.PIEIER9.bit.INTx3=1;     // PIE Group 9, INT3, RX SCI-B
	PieCtrlRegs.PIEIER9.bit.INTx4=1;     // PIE Group 9, INT4, TX SCI-B
	PieCtrlRegs.PIEIER8.bit.INTx5=1;     // PIE Group 8, int5, RX SCI-C
	
	IER = 0x180;	// Enable CPU INT, Level8 and Level9 only
	
	EINT; // enable INTs
}
